<script setup>
import axios from '../request.js';
import {onMounted, ref, onBeforeUnmount} from "vue";
import {Search} from '@element-plus/icons-vue';
import {ElMessage, ElNotification} from 'element-plus';

const hotQuestions = ref([]); // 热门问题列表
const inputValue = ref("");
const show = ref(false); //
const questions = ref([]);
const showQuestions = ref(false);
const QAList = ref([]);
const ws = ref(null);
const inputMessage = ref('');
const receiveMessages = ref([]);
const username = ref('')
const managerName = ref('')
const managerStatus = ref()
const userAvatar = ref("https://q7.itc.cn/q_70/images03/20240423/6d236fae5c8f44ed9b60d977f32debb7.jpeg")
const adminAvatar = ref("https://q5.itc.cn/q_70/images03/20240409/2013315961114923a8c53c8b21b30bda.jpeg")
const historicalMessages = ref([]);

// 错误处理函数
const handleError = (error) => {
  console.error('Error:', error);
  ElNotification({
    title: 'Error',
    message: '出现错误，请稍后再试。',
    type: 'error',
  });
};

// 点击切换显示的函数
const clickShow = (manual) => {
  show.value = manual;
};

let timer;

// 生命周期钩子：组件挂载时执行
onMounted(() => {
  getQuestions();
  getStatus();
  timer = setInterval(getStatus, 5000);
});

// 获取热门问题的函数
const getQuestions = () => {
  axios.get("/customerService/getQuestionByHits").then(resp => {
    username.value = resp.message;
    hotQuestions.value = resp.date;
  })
      .catch(handleError);
};

// 模糊查询功能的函数
const fuzzyQuery = () => {
  if (!inputValue.value.trim()) {
    ElNotification({
      title: 'Message',
      message: '请输入你的问题',
      type: 'message',
    });
    return;
  }

  axios.get("/customerService/getQuestionByContent", {
    params: {content: inputValue.value}
  })
      .then(resp => {
        if (resp.length === 0) {
          ElNotification({
            title: 'Warning',
            message: '没有相关问题',
            type: 'warning',
          });
          return;
        }
        questions.value = resp;
        showQuestions.value = true;
      })
      .catch(handleError);
};

// 获取当前时间的函数
const getCurrentTime = () => {
  return new Date();
};

// 格式化时间的函数
const formatTime = (time) => {
  return time.toLocaleString();
};

// 根据问题ID获取答案的函数
//并将该问题的点击量加1
const getAnswer = (id, questionContent) => {
  const now = getCurrentTime();
  const tenMinutesAgo = new Date(now.getTime() - 10 * 60 * 1000);

  // 检查是否在10分钟内已经点击过相同的问题
  const recentSameQuestion = QAList.value.find(item => item.id === id && item.timestamp > tenMinutesAgo);

  if (recentSameQuestion) {
    ElNotification({
      title: 'Warning',
      message: '该问题已在10分钟内询问过。',
      type: 'warning',
    });
    showQuestions.value = false;
    return;
  }

  axios.get("/customerService/getAnswerByQuestionId", {
    params: {questionId: id}
  }).then(resp => {
    const time = getCurrentTime();
    QAList.value.push({type: 'time', content: formatTime(time), timestamp: time});
    if (resp.length > 0) {
      QAList.value.push({type: 'question', content: questionContent, id: id, timestamp: time},);
      resp.forEach(answer => {
        QAList.value.push({type: 'answer', content: answer.answerContent, id: id, timestamp: time});
      });
      showQuestions.value = false;
    } else {
      ElNotification({
        title: 'Warning',
        message: '没有相关答案',
        type: 'warning',
      });
    }
  })
      .catch(handleError);
};

//获取客服状态
const getStatus = () => {
  axios.get("/customerService/getManagerStatusByManagerName").then(resp => {
    managerStatus.value = resp.date;
  })
}

//获取历史聊天记录
const getHistoricalMessages = (username, managerName) => {
  axios.get("/customerService/getMessagesByUserNames", {
    params: {fromUserName: username, toUserName: managerName}
  }).then(resp => {
    if (resp.length <= 0) {
      ElMessage({
        title: 'Warning',
        message: '没有聊天记录',
        type: 'warning',
      });
    } else {
      historicalMessages.value = resp;
    }
  })
}

const clickChat = (name) => {
  // 清空聊天消息
  receiveMessages.value = [];

  // 断开当前的 WebSocket 连接（如果有）
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.close();
  }

  // 以新的管理员名称建立新的 WebSocket 连接
  connectWebSocket(username.value);
  managerName.value = name;
};

// 建立 WebSocket 连接的函数
const connectWebSocket = (username) => {

  const wsUrl = `ws://localhost:8090/imserver/${username}`; // 替换为你的 WebSocket 服务器 URL

  // 创建 WebSocket 连接
  ws.value = new WebSocket(wsUrl);

  // WebSocket 事件监听器
  ws.value.onopen = () => {
    console.log('WebSocket 连接已建立');
    notifyManager(managerName.value);
  };

  ws.value.onmessage = handleMessage;

  ws.value.onerror = handleError1;

  ws.value.onclose = handleClose;
};

const notifyManager = (managerName) => {
  const msg = JSON.stringify({type: 'notifyManager', manager: managerName, from: username.value});
  sendMessageToServer(msg);
};

// 处理收到的消息的函数
const handleMessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.text === 'empty') {
    ElMessage({
      message: '服务端收到的问题为空',
      type: 'error',
    })
    return;
  } else if (msg.type === 'error') {
    alert("管理员正在连接中，请稍等")
    return;
  } else if (msg.type === 'notifyUser') {
    alert(`${msg.from} 已在线，可以开始询问`)
    return;
  }
  // 更新 receiveMessages 数组
  receiveMessages.value.push(msg);
  console.log(receiveMessages)
};

// 处理错误的函数
const handleError1 = (error) => {
  console.error('WebSocket 错误:', error);
};

// 处理连接关闭的函数
const handleClose = () => {
  console.log('WebSocket 连接已关闭');
};

// 构建和准备消息的内容
const prepareMessage = () => {
  if (!inputMessage.value.trim()) {
    ElMessage({
      message: '请输入要询问的内容',
      type: 'warning',
    });
    return;
  }
  const msg = JSON.stringify({type: 'chat', text: inputMessage.value, from: username.value, to: managerName.value});
  sendMessageToServer(msg);
  // 清空输入框内容
  inputMessage.value = '';
};

// 向 WebSocket 服务器发送消息的函数
const sendMessageToServer = (message) => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.send(message);
  } else {
    console.error('WebSocket 连接未建立');
  }
};

// 在组件卸载时断开 WebSocket 连接的钩子
onBeforeUnmount(() => {
  if (ws.value && ws.value.readyState === WebSocket.OPEN) {
    ws.value.close();
  }
  // 在组件销毁前清除定时器
  clearInterval(timer);
});
</script>

<template>
  <el-container>

    <!-- 侧边栏，包含智能和手动频道的导航 -->
    <el-aside width="200px">
      <el-menu>
        <el-sub-menu index="1" @click="clickShow(false)">
          <template #title>智能通道</template>
        </el-sub-menu>
      </el-menu>
      <el-menu>
        <el-sub-menu index="1" @click="clickShow(true)">
          <template #title>人工通道</template>
          <el-menu-item index="1-1" @click="clickChat('manager1')">管理员1
            <span v-if="managerStatus"
                  :style="{color: managerStatus.find(item => item.managerName === 'manager1')?.status === 1 ? 'green' : 'red'}"
            >
              （{{ managerStatus.find(manager => manager.managerName === 'manager1')?.status === 1 ? '在线' : '离线' }}）
            </span>
          </el-menu-item>
          <el-menu-item index="1-2" @click="clickChat('manager2')">管理员2
            <span v-if="managerStatus"
                  :style="{color: managerStatus.find(item => item.managerName === 'manager2')?.status === 1 ? 'green' : 'red'}"
            >
              （{{ managerStatus.find(manager => manager.managerName === 'manager2')?.status === 1 ? '在线' : '离线' }}）
            </span>
          </el-menu-item>
          <el-sub-menu index="1-3">
            <template #title>备用客服</template>
            <el-menu-item index="1-3-1" @click="clickChat('manager3-1')">管理员3-1
              <span v-if="managerStatus"
                    :style="{color: managerStatus.find(item => item.managerName === 'manager3-1')?.status === 1 ? 'green' : 'red'}"
              >
                （{{
                  managerStatus.find(manager => manager.managerName === 'manager3-1')?.status === 1 ? '在线' : '离线'
                }}）
              </span>
            </el-menu-item>
          </el-sub-menu>
        </el-sub-menu>
      </el-menu>
    </el-aside>

    <el-container class="customer-card" v-if="!show">
      <el-header class="header">网咖客服中心</el-header>

      <el-main class="chat-main">
        <!-- 热门问题展示 -->
        <div class="a1">
          <el-card class="card">
            <template #header>
              <div class="card-header">热门问题</div>
            </template>
            <p v-for="(question, index) in hotQuestions" :key="index"
               @click="getAnswer(question.id, question.questionContent)">
              {{ question.id }}. {{ question.questionContent }}
            </p>
          </el-card>

          <!-- 问答展示 -->
          <div class="chat-container">
            <div v-for="(item, index) in QAList" :key="index">
              <div v-if="item.type === 'time'" class="chat-time">{{ item.content }}</div>
              <div v-else :class="item.type === 'question' ? 'chat-right' : 'chat-left'">
                {{ item.content }}
              </div>
            </div>
          </div>
        </div>

        <!-- 相关问题展示，点击显示 -->
        <div v-if="showQuestions" class="a2">
          <el-card class="card1">
            <template #header>
              <div class="card-header">猜你想问：</div>
            </template>
            <p v-for="(question, i) in questions" :key="i" @click="getAnswer(question.id, question.questionContent)">
              {{ i + 1 }}. {{ question.questionContent }}
            </p>
          </el-card>
        </div>
      </el-main>

      <!-- 输入框和查询按钮 -->
      <el-footer class="chat-footer">
        <el-input v-model="inputValue" style="width: 240px" size="large" placeholder="Search related questions"
                  :prefix-icon="Search"/>
        <el-button @click="fuzzyQuery" circle>
          <el-icon>
            <Search/>
          </el-icon>
        </el-button>
      </el-footer>
    </el-container>

    <el-container class="labour" v-if="show">
      <el-header class="header">网咖客服中心</el-header>

      <el-main class="chat-main">
        <div class="chat-container1">

          <div v-for="(msg, index) in historicalMessages" :key="index"
               :class="msg.fromUserName === username ? 'chat-right1' : 'chat-left1'">
            <div class="userInfo">
              <span class="username">{{ msg.fromUserName }}</span>
              <img :src="msg.fromUserName === username ? userAvatar : adminAvatar" class="avatar"/>
            </div>
            <p class="message-text">{{ msg.messagesText }}</p>
          </div>
          <span @click="getHistoricalMessages(username,managerName)">聊天历史</span>

          <div v-for="(msg, index) in receiveMessages" :key="index"
              :class="msg.from === username ? 'chat-right1' : 'chat-left1'">
            <div class="userInfo">
              <span class="username">{{ msg.from }}</span>
              <img :src="msg.from === username ? userAvatar : adminAvatar" class="avatar"/>
            </div>
            <p class="message-text">{{ msg.text }}</p>
          </div>

        </div>
      </el-main>

      <el-footer class="chat-footer">
        <div class="input-container">
          <el-input v-model="inputMessage" placeholder="输入消息" class="input-box"/>
          <el-button @click="prepareMessage" type="primary">发送消息</el-button>
        </div>
      </el-footer>

    </el-container>

  </el-container>
  <div class="return">
    <router-link to="/index" class="return-router-link">返回首页</router-link>
    <router-link to="/RechargeCard" class="return-router-link">返回充值页</router-link>
  </div>
</template>

<style scoped>
.el-container {
  width: 900px;
  height: 650px;
  display: flex;
}

.customer-card {
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;
  width: 100%;
}

.header {
  background-color: #f53e3e;
  color: white;
  font-size: 20px;
  text-align: center;
  padding: 15px 0;
}

.card, .card1 {
  margin: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-size: 18px;
  color: #333;
  padding: 10px;
}

.chat-main {
  flex-grow: 1;
  overflow-y: auto;
}

.chat-container {
  margin: 20px;
  display: flex;
  flex-direction: column;
}

.chat-left, .chat-right {
  padding: 10px;
  border-radius: 10px;
  margin: 5px 0;
}

.chat-left {
  background-color: #d1ecf1;
  text-align: left;
  align-self: flex-start;
}

.chat-right {
  background-color: #c3e6cb;
  text-align: right;
  align-self: flex-end;
}

.chat-time {
  text-align: center;
  color: #888;
  margin: 5px 0;
}

.chat-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 20px;
  background-color: #f6f6f6;
}

.el-input {
  margin-right: 10px;
}

.labour {
  display: flex;
  flex-direction: column;
  background-color: #f6f6f6;
  width: 100%;
}

.chat-main {
  flex-grow: 1;
  overflow-y: auto;
}

.chat-container1 {
  display: flex;
  flex-direction: column;
}

.chat-left1, .chat-right1 {
  display: flex;
  align-items: flex-start;
  margin: 10px 0;
}

.chat-left1 {
  flex-direction: row;
  align-self: flex-start;
}

.chat-right1 {
  flex-direction: row-reverse;
  align-self: flex-end;
}

.userInfo {
  display: flex;
  flex-direction: column; /* 垂直方向排列 */
  align-items: center; /* 水平居中对齐 */
}

.avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin: 5px;
}

.username {
  font-weight: bold;
  color: #333;
}

.message-text {
  background-color: #cde0fd;
  padding: 10px;
  border-radius: 10px;
  margin: auto;
  color: #333;
  max-width: 500px; /* 设置最大宽度 */
  word-wrap: break-word; /* 设置自动换行 */
}

.chat-right .message-text {
  background-color: #cce5ff;
}

.input-container {
  display: flex;
  align-items: center;
  width: 100%;
}

.input-box {
  flex-grow: 1;
  margin-right: 10px;
}

.return {
  margin: 10px 0 0 0;
}

.return-router-link {
  text-decoration: none;
  margin: 0 30px 0 20px;
  color: black;
}

.return-router-link:hover {
  color: #f53e3e;
}
</style>
